#coding=utf-8
import stutils
stutils.set_django_environ()
from djstock.shstock.models import *

def sum_amount(qd):
    return sum( [d.amount for d in qd] )
def max_amount(qd):
    pass
def min_amount(qd):
    pass
    
def qsdeal_stats(qd):
    '''基本统计的情况:
    n:总比数;nb:买盘比数;ns:卖盘比数;
    amount_sum:总成交金额;
    buy_sell:买盘 - 卖盘的金额;
    '''
    #总比数
    n = qd.count()
    #总成交金额
    amount_sum = sum_amount(qd)
    
    #金额: 买盘 - 卖盘
    bd = qd.filter(buyorsell='b')
    sd = qd.filter(buyorsell='s')
    
    nb = bd.count()
    ns = sd.count()
    buy_sell = sum_amount(bd) - sum_amount(sd)
    
    result = {'n':n, 'nb':nb, 'ns':ns, 'amount_sum':amount_sum, 'buy_sell':buy_sell}
    return result
class NoDealError(Exception):
    def __str__(self):
        return "No Deal data provided."
    
class DealAnalyser(object):
    
    def __init__(self, share, deal):
        if not isinstance(deal, models.query._QuerySet):
            raise TypeError("Deals to be analyed should be django's 'models.query._QuerySet' type")
        if deal.count() == 0:
            raise NoDealError()
            
        self.share = share
        self.qsdeal = deal
        
    def price_distribution(self):pass
    
    def basic_stats(self):
        return qsdeal_stats(self.qsdeal)
    
    #一些大单追踪的method
    def stats_filterby(self, **kwargs):
        '''
        eg: filter_by(amount_gte=1000000);filter_by(amount_lte=10000)
            filter_by(quantity_gte=40000);filter_by(quantity_lte=500)        
        '''
        assert len(kwargs) == 1
        qsd = self.qsdeal.filter(**kwargs)
        return qsdeal_stats(qsd)
        
        
        
        
        
